package com.flyqiu.flow.core.var;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.flyqiu.flow.api.script.IVarSerialize;
import com.flyqiu.flow.api.script.FlyQiuFlowVarSerializeManage;
import com.flyqiu.flow.api.script.VarSerialize;

import java.util.Collection;

public class JSONArrayConverter implements IVarSerialize {
    private static final String TYPE_KEY = JSONArray.class.getName();

    @Override
    public String type() {
        return TYPE_KEY;
    }

    @Override
    public boolean isType(FlyQiuFlowVarSerializeManage manage, Object val) {
        if (val instanceof JSONArray) {
            return true;
        } else if (val instanceof Collection) {
            return true;
        } else if (val instanceof String) {
            return JSON.isValidArray((String) val);
        }
        return val.getClass().isArray();
    }

    @Override
    public VarSerialize serialize(FlyQiuFlowVarSerializeManage manage, Object val) {
        if (val instanceof JSONArray) {
            return new VarSerialize(TYPE_KEY, ((JSONArray) val).toJSONString(), false);
        } else if (val instanceof Collection) {
            return new VarSerialize(TYPE_KEY, JSONArray.toJSONString(val), false);
        } else if (val instanceof String) {
            return new VarSerialize(TYPE_KEY, (String) val, false);
        } else if (val.getClass().isArray()) {
            return new VarSerialize(TYPE_KEY, JSONArray.toJSONString(val), false);
        }
        return null;

    }

    @Override
    public Object deserialize(FlyQiuFlowVarSerializeManage manage, String val) {
        return JSONArray.parseArray(val);
    }
}
